package com.seele.tigerwallet.ui.views;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.EditText;

import com.seele.tigerwallet.R;

@SuppressLint("AppCompatCustomView")
public class LineEditText extends EditText {


    private String fixedText;
    /**下滑线的颜色**/
    private int line_corlor  ;

    /**下滑线的高度**/
    private int line_height ;

    /**画笔**/
    private Paint mPaint ;


    public LineEditText(Context context){
        //调用两个参数的构造方法
        this(context,null) ;
    }
    /**
     * 加载xml的时候调用这个构造方法
     * @param context
     * @param attrs
     */
    public LineEditText(Context context, AttributeSet attrs){
        //调用三个参数的构造方法
        this(context, attrs, android.R.attr.editTextStyle);
    }

    public LineEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        initTypeArray(context, attrs, defStyle);
        initPaint();
    }



    public void setFixedText(String text) {
        fixedText = text;
        int left = (int) getPaint().measureText(fixedText)+ getPaddingLeft();
        setPadding(left, getPaddingTop(), getPaddingBottom(), getPaddingRight());
        invalidate();
    }


    /**初始化Paint***/
    private void initPaint() {
        mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(line_height) ;
        mPaint.setColor(line_corlor);
    }
    /***
     * 初始化TypedArray
     * @param context
     * @param attrs
     * @param defStyle
     */
    private void initTypeArray(Context context, AttributeSet attrs, int defStyle) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.edittext_bg, defStyle, 0) ;
        int n = a.getIndexCount() ;
        for (int i = 0; i < n; i++) {
            int attr = a.getIndex(i) ;
            switch (attr) {
                case R.styleable.edittext_bg_line_color:
                    //从xml取得下滑线的颜色 默认是绿色
                    line_corlor = a.getColor(attr, Color.GREEN) ;
                    break;
                case R.styleable.edittext_bg_line_height:
                    //从xml取得下滑线的高 默认是1dip   dip to px
                    line_height = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics())) ;
                    break ;
            }
        }
        //使用完一定要recycle 保证资源回收
        a.recycle() ;
    }



    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 画底线
        canvas.drawLine(0, this.getHeight()-1, this.getWidth()-1,this.getHeight()-1, mPaint);
    }
}
